import ryu.app.simple_switch_13
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER, set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ipv4
from ryu.lib.packet import tcp
from ryu.lib.packet import ether_types
from ryu.ofproto import ether

client = {'ip': '10.0.1.5', 'mac': '00:00:00:00:00:03'}
server1 = {'ip': '10.0.1.2', 'mac': '00:00:00:00:00:01'}
server2 = {'ip': '10.0.1.3', 'mac': '00:00:00:00:00:02'}

class TrafficRedirectionApp(ryu.app.simple_switch_13.SimpleSwitch13):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(TrafficRedirectionApp, self).__init__(*args, **kwargs)
        self.mac_to_port = {}
        print("TrafficRedirectionApp initialized")

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        """
        Handler for switch features event.
        """
        try:
            datapath = ev.msg.datapath
            self.install_table_miss_flow(datapath)
        except Exception as e:
            print(f"Exception in switch_features_handler: {e}")

    def install_table_miss_flow(self, datapath):
        """
        Install table-miss flow entry.
        """
        try:
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            match = parser.OFPMatch()
            actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]
            self.add_flow(datapath, 0, match, actions)
        except Exception as e:
            print(f"Exception in install_table_miss_flow: {e}")

    def add_flow(self, datapath, priority, match, actions, buffer_id=None, idle_timeout=5):
        """
        Add a flow entry to the datapath.
        """
        try:
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id, priority=priority, match=match,
                                    instructions=inst, idle_timeout=idle_timeout)
            datapath.send_msg(mod)
        except Exception as e:
            print(f"Exception in add_flow: {e}")

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        """
        Handler for packet in event.
        """
        try:
            msg = ev.msg
            datapath = msg.datapath
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            in_port = msg.match['in_port']

            pkt = packet.Packet(msg.data)
            eth = pkt.get_protocols(ethernet.ethernet)[0]

            if eth.ethertype == ether_types.ETH_TYPE_LLDP:
                return

            dst = eth.dst
            src = eth.src
            dpid = datapath.id

            self.mac_to_port.setdefault(dpid, {})
            print(f"Packet in {dpid} {src} {dst} {in_port}")
            self.mac_to_port[dpid][src] = in_port

            out_port = self.mac_to_port[dpid].get(dst, ofproto.OFPP_FLOOD)
            actions = [parser.OFPActionOutput(out_port)]

            if out_port != ofproto.OFPP_FLOOD:
                match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
                self.add_flow(datapath, 1, match, actions)

            data = msg.data if msg.buffer_id == ofproto.OFP_NO_BUFFER else None
            self.send_packet_out(datapath, msg.buffer_id, in_port, actions, data)

            ip_pkt = pkt.get_protocol(ipv4.ipv4)
            tcp_pkt = pkt.get_protocol(tcp.tcp)
            if ip_pkt and tcp_pkt and tcp_pkt.bits == tcp.TCP_SYN:
                print("TCP SYN packet detected")
                self.redirect_traffic(datapath, in_port, ip_pkt, tcp_pkt)
        except Exception as e:
            print(f"Exception in _packet_in_handler: {e}")

    def send_packet_out(self, datapath, buffer_id, in_port, actions, data):
        """
        Send packet out.
        """
        try:
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            out = parser.OFPPacketOut(datapath=datapath, buffer_id=buffer_id,
                                      in_port=in_port, actions=actions, data=data)
            datapath.send_msg(out)
        except Exception as e:
            print(f"Exception in send_packet_out: {e}")

    def redirect_traffic(self, datapath, in_port, ip_pkt, tcp_pkt):
        """
        Redirect traffic to server2.
        """
        try:
            parser = datapath.ofproto_parser
            ofproto = datapath.ofproto

            match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                    ipv4_src=ip_pkt.src,
                                    ipv4_dst=ip_pkt.dst,
                                    ip_proto=ip_pkt.proto,
                                    tcp_src=tcp_pkt.src_port,
                                    tcp_dst=tcp_pkt.dst_port)

            actions = [parser.OFPActionSetField(eth_dst=server2['mac']),
                       parser.OFPActionSetField(ipv4_dst=server2['ip']),
                       parser.OFPActionOutput(ofproto.OFPP_IN_PORT)]

            self.add_flow(datapath, 2, match, actions)

            self.send_packet_out(datapath, ofproto.OFP_NO_BUFFER, in_port, actions, None)
        except Exception as e:
            print(f"Exception in redirect_traffic: {e}")

if __name__ == "__main__":
    print("Starting TrafficRedirectionApp")



